package org.api.free.service.ocr;

import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.api.free.config.TessertactConfig;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

@Service
@Slf4j
public class OcrService {
    @Resource
    private TessertactConfig tessConfig;


    public String recognizeText(MultipartFile file) throws TesseractException {
        // 创建临时文件
        File convFile = new File(System.getProperty("java.io.tmpdir") + "/" + file.getOriginalFilename());
        try {
            file.transferTo(convFile);
            // 保存上传文件
            Tesseract tesseract = new Tesseract();
            // 设置tessdata路径（根据系统调整）
            tesseract.setDatapath(tessConfig.getDatadir());
            tesseract.setLanguage("eng+chi_sim");
            // 使用中英文混合识别
            return tesseract.doOCR(convFile);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            convFile.delete(); // 删除临时文件
        }
    }


    public String recognizeTextCmd(MultipartFile file) throws TesseractException {
        // 创建临时文件
        String uuid = UUID.randomUUID().toString();
        String tmpDir = tessConfig.getTmpdir();
        File convFile = new File(tmpDir + uuid + "_" + file.getOriginalFilename());
        File targetFIle = new File(tmpDir + uuid + ".txt");
        try {
            // 保存上传文件
            file.transferTo(convFile);
            String cmd = "tesseract  -l eng+chi_sim " + convFile.getAbsolutePath() + "  " + tmpDir + uuid;
            Process process = Runtime.getRuntime().exec(cmd);
            int exitCode = process.waitFor();
            log.info("退出码: {}", exitCode);
            return readAbsolutePathFile(targetFIle.getAbsolutePath());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public String readAbsolutePathFile(String path) throws IOException {
        return new String(Files.readAllBytes(Paths.get(path)));
    }
}